//
//  BeAppJsonAdapto.m
//  MClient
//
//  Created by  史正烨 on 09-9-28.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MServerJsonDAO.h"
#import "MClientAppDelegate.h"
#import "SBJSON.h"
#import "MServerConfigCache.h"
#import "MCUserDefaults.h"
#import "MCErrorManagement.h"
#import "LoginBox.h"

@interface MServerJsonDAO (Private)
- (void)sendAsyncJsonMessage;
- (id)sendSyncJsonMessage:(NSString *)aMethodName parameters:(NSMutableDictionary *)aParameters;
- (void)saveToConfigCache:(id)cacheValue;
@end

@implementation MServerJsonDAO
//@synthesize returnCode;
//@synthesize returnMessage;
//@synthesize returnValue;
//@synthesize responseData;
@synthesize cacheType;
@synthesize httpConnection;
@synthesize responseData;

static NSString *serverServletUrl = nil;
static NSArray *cookies = nil;

#pragma mark ---- 类基本方法 ----

- (id)init {
	if (self = [super init]) {
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(delegateInvalid:)
													 name:@"viewControllerDealloc" object:nil];
	}
	return self;
}

#pragma mark ---处理接收到的消息---
- (void)delegateInvalid:(NSNotification *)notification
{
	if ([notification object] == delegate) {
		delegate = nil;
	}
	//MClientAppDelegate *appDelegate = (MClientAppDelegate*)[[UIApplication sharedApplication] delegate];
	//[appDelegate stopActivityIndicatorView];//huotianjun 注释掉，不知道对MCGridMenuView,MCImageView,MCTableCell,MCViewController发出的解构通知有何影响，待观察。
}

- (void)dealloc {
	MCLog(@"-----------%@ dealloc------------", [self description]);
	[responseData release];responseData = nil;
	[cacheType release];cacheType = nil;
	[httpConnection cancel];
	[httpConnection release];httpConnection = nil;
	[[NSNotificationCenter defaultCenter] removeObserver:self 
													name:@"viewControllerDealloc" 
												  object:nil];	
	[super dealloc];
}

- (void)initServerUrl {
	MCUserDefaults *defaults = [MCUserDefaults instance];
	
	NSString *serverUrl;
	if ([defaults.current_ServerUrl length] == 0) {
		serverUrl = [MClientAppDelegate getDefaultServerUrl];
	} else {
		serverUrl = defaults.current_ServerUrl;
	}
	
	serverServletUrl = [[serverUrl
						 stringByAppendingFormat:@"/beapp/MobileCommunicationServletV4"] copy];
}

+ (NSArray *)getCookies {
	return cookies;
}

+ (NSString *)getServerServletUrl {
	return serverServletUrl;
}

+ (void)setServerServletUrl:(NSString *)url {
	serverServletUrl = [url copy];
}

#pragma mark ---- 实现MServerDAOProtocol方法 ----

- (void)loginAsync:(NSString *)partyId 
			userId:(NSString *)userId 
		  password:(NSString *)password
			  imei:(NSString *)imei 
			  imsi:(NSString *)imsi 
			 acode:(NSString *)acode 
		  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	if (nil == acode || [@"" isEqualToString:acode]) {
		inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
						partyId,@"pid",
						userId,@"uid",
						password,@"pwd",
						imei,@"imei",
						imsi,@"imsi",
						[MCUserDefaults instance].deviceToken,@"deviceToken",nil];
	} else {
		inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
						partyId,@"pid",
						userId,@"uid",
						password,@"pwd",
						imei,@"imei",
						imsi,@"imsi",
						acode,@"acode",
						[MCUserDefaults instance].deviceToken,@"deviceToken",nil];
	}
	
	methodName = @"login";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (id)login:(NSString *)partyId 
	 userId:(NSString *)userId 
   password:(NSString *)password 
	   imei:(NSString *)imei
	   imsi:(NSString *)imsi
	  acode:(NSString *)acode {
	
	NSMutableDictionary *parameters;
	if (nil == acode || [@"" isEqualToString:acode]) {
		parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					  partyId,@"pid",
					  userId,@"uid",
					  password,@"pwd",
					  imei,@"imei",
					  imsi,@"imsi",nil];
	} else {
		parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					  partyId,@"pid",
					  userId,@"uid",
					  password,@"pwd",
					  imei,@"imei",
					  imsi,@"imsi",
					  acode,@"acode",nil];
	}
	
	return [self sendSyncJsonMessage:@"login" parameters:parameters];
}

- (void)logoutAsync {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] init];
	
	methodName = @"logout";
	delegate = nil;	
	
	[self sendAsyncJsonMessage];
}

- (void)getAppsAsync:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] init];
	
	methodName = @"getApps";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (id)getMenuOfApp:(NSString *)appId {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   appId,@"id",nil];
	
	return [self sendSyncJsonMessage:@"getMenuOfApp" parameters:parameters];
}

- (void)getMenuOfAppAsync:(NSString *)appId 
			  otherParams:(NSMutableDictionary *)otherParams
				 delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					appId,@"id",nil];	
	
	methodName = @"getMenuOfApp";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (id)getSubMenu:(NSString *)menuId {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   menuId,@"id",nil];
	
	return [self sendSyncJsonMessage:@"getSubMenu" parameters:parameters];
}

- (void)getSubMenuAsync:(NSString *)menuId 
			otherParams:(NSMutableDictionary *)otherParams
			   delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					menuId,@"id",nil];
	
	methodName = @"getSubMenu";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (void)getMenuConfigAsync:(NSString *)menuId //huotianjun 没有用到？
				  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					menuId,@"id",nil];
	
	methodName = @"getMenuConfig";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)getListSizeAsync:(NSString *)dataObjectName 
			  layoutName:(NSString *)layoutName 
			 queryFilter:(NSMutableArray *)queryFilter
				delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					dataObjectName,@"dto",
					layoutName,@"layout",
					queryFilter,@"ft",nil];
	
	methodName = @"getListSize";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (id)getListConfig:(NSString *)dataObjectName 
		 layoutName:(NSString *)layoutName {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   dataObjectName,@"dto",
									   layoutName,@"layout",nil];
	
	return [self sendSyncJsonMessage:@"getListConfig" parameters:parameters];
}

- (void)getListConfigAsync:(NSString *)dataObjectName 
				layoutName:(NSString *)layoutName 
			   otherParams:(NSMutableDictionary *)otherParams
				  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					dataObjectName,@"dto",
					layoutName,@"layout",nil];
	
	methodName = @"getListConfig";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (id)getListData:(NSString *)dataObjectName 
	   layoutName:(NSString *)layoutName 
	  queryFilter:(NSMutableArray *)queryFilter 
			 page:(int)page {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   dataObjectName,@"dto",
									   layoutName,@"layout",
									   queryFilter,@"ft",
									   [NSString stringWithFormat:@"%d",page],@"p",nil];
	
	return [self sendSyncJsonMessage:@"getListData" parameters:parameters];
}

- (void)getListDataAsync:(NSString *)dataObjectName 
			  layoutName:(NSString *)layoutName 
			 queryFilter:(NSMutableArray *)queryFilter 
					page:(int)page 
				delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					dataObjectName,@"dto",
					layoutName,@"layout",
					queryFilter,@"ft",
					[NSString stringWithFormat:@"%d",page],@"p",nil];
	
	methodName = @"getListData";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (id)getFormConfig:(NSString *)dataObjectName 
		 layoutName:(NSString *)layoutName 
		   editable:(NSString *)editable{
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   dataObjectName,@"dto",
									   layoutName,@"layout",
									   editable,@"e",nil];
	
	return [self sendSyncJsonMessage:@"getFormConfig" parameters:parameters];
}

- (void)getFormConfigAsync:(NSString *)dataObjectName 
				layoutName:(NSString *)layoutName 
				  editable:(NSString *)editable 
			   otherParams:(NSMutableDictionary *)otherParams
				  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					dataObjectName,@"dto",
					layoutName,@"layout",
					editable,@"e",nil];
	
	methodName = @"getFormConfig";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (id)getFormData:(NSString *)dataObjectName 
	   layoutName:(NSString *)layoutName 
			  key:(NSString *)key 
	   isEditable:(NSString *)editable {	
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   dataObjectName,@"dto",
									   layoutName,@"layout",
									   key,@"key",
									   editable,@"e",nil];
	
	return [self sendSyncJsonMessage:@"getFormData" parameters:parameters];
	
}

- (void)getFormDataAsync:(NSString *)dataObjectName 
			  layoutName:(NSString *)layoutName 
					 key:(NSString *)key 
			  isEditable:(NSString *)editable
				delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					dataObjectName,@"dto",
					layoutName,@"layout",
					key,@"key",
					editable,@"e",nil];
	
	methodName = @"getFormData";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (id)saveFormData:(NSString *)buttonId 
		buttonType:(NSString *)buttonType 
	dataObjectName:(NSString *)dataObjectName
		  formData:(NSMutableDictionary *)formData {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId,@"bid",
									   buttonType,@"bty",
									   dataObjectName,@"dto",
									   formData,@"r",nil];
	
	return [self sendSyncJsonMessage:@"saveFormData" parameters:parameters];
}

- (void)saveFormDataAsync:(NSString *)buttonId 
			   buttonType:(NSString *)buttonType 
		   dataObjectName:(NSString *)dataObjectName 
				 formData:(NSMutableDictionary *)formData 
			  otherParams:(NSMutableDictionary *)otherParams
				 delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					buttonId,@"bid",
					buttonType,@"bty",
					dataObjectName,@"dto",
					formData,@"r",nil];
	
	methodName = @"saveFormData";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (id)deleteData:(NSString *)buttonId 
	  buttonType:(NSString *)buttonType 
  dataObjectName:(NSString *)dataObjectName 
			keys:(NSMutableArray *)keys {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId, @"bid",
									   buttonType, @"bty",
									   dataObjectName,@"dto",
									   keys,@"keys",nil];
	return [self sendSyncJsonMessage:@"deleteData" parameters:parameters];
}

- (void)deleteDataAsync:(NSString *)buttonId 
			 buttonType:(NSString *)buttonType 
		 dataObjectName:(NSString *)dataObjectName 
				   keys:(NSMutableArray *)keys 
			otherParams:(NSMutableDictionary *)otherParams
			   delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					buttonId,@"bid",
					buttonType,@"bty",
					dataObjectName,@"dto",
					keys,@"keys",nil];
	
	methodName = @"deleteData";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

-  (id)doServiceByRecord:(NSString *)buttonId 
			  buttonType:(NSString *)buttonType 
		  dataObjectName:(NSString *)dataObjectName 
				 records:(NSMutableArray *)records {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId,@"bid",
									   buttonType,@"bty",
									   dataObjectName,@"dto",
									   records,@"r",nil];
	
	return [self sendSyncJsonMessage:@"doServiceByRecord" parameters:parameters];
	
}

- (void)doServiceByRecordAsync:(NSString *)buttonId 
					buttonType:(NSString *)buttonType 
				dataObjectName:(NSString *)dataObjectName 
					   records:(NSMutableArray *)records 
				  serviceDefId:(NSString *)serviceDefId 
				   otherParams:(NSMutableDictionary *)otherParams
					  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					buttonId,@"bid",
					buttonType,@"bty",
					dataObjectName,@"dto",
					records,@"r",
					serviceDefId,@"sid",nil];
	
	methodName = @"doServiceByRecord";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

-  (void)calcAsync:(NSString *)lookupBack
	dataObjectName:(NSString *)dataObjectName 
		   records:(NSMutableArray *)records 
	  serviceDefId:(NSString *)serviceDefId 
		  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					lookupBack,@"lub",
					dataObjectName,@"dto",
					records,@"r",
					serviceDefId,@"sid",nil];
	
	methodName = @"calc";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}


- (id)getTree:(NSString *)treeId
  queryFilter:(NSMutableArray *)queryFilter{
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   treeId,@"id",
									   queryFilter,@"ft",nil];
	
	return [self sendSyncJsonMessage:@"getTree" parameters:parameters];
	
}

- (void)getTreeAsync:(NSString *)treeId 
		 queryFilter:(NSMutableArray *)queryFilter 
			delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					treeId,@"id",
					queryFilter,@"ft",nil];
	
	methodName = @"getTree";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)getNodeAsync: (NSString *)nid 
			  treeId:(NSString *)treeId 
		 queryFilter:(NSMutableArray *)queryFilter 
			   param:(NSMutableDictionary *)param 
			delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					nid,@"nid",
					treeId,@"id",
					queryFilter,@"ft",
					param,@"fp",nil];
	
	methodName = @"getNode";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
	
}

- (id)getReportConfig:(NSString *)reportName {
	
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   reportName,@"name",nil];
	return [self sendSyncJsonMessage:@"getReportConfig" parameters:parameters];
}

- (void)getReportConfigAsync:(NSString *)reportName
				 otherParams:(NSMutableDictionary *)otherParams
					delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					reportName,@"name",nil];
	
	methodName = @"getReportConfig";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (void)modifyPasswordAsync:(NSString *)oldPassword 
				   password:(NSString *)password 
				   delegate:(id<MCServer2ViewDelegate>)aDelegate{
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
					oldPassword,@"opwd",
					password,@"pwd",nil];
	
	methodName = @"modifyPassword";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)downloadAsync:(NSString *)actionType
			 dataFrom:(NSString *)dataFrom 
				param:(NSMutableDictionary *)param 
			 delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					actionType,@"at",
					dataFrom,@"df",
					param,@"fp",
					nil];
	
	methodName = @"downLoad";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)uploadAsync:(NSString *)data 
		   delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					data,@"data",
					nil];
	
	methodName = @"upload";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)getUploadFileNameAsync:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] init];
	
	methodName = @"getUploadFileName";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)getCustomFormAsync:(NSString *)key
				layoutName:(NSString *)layoutName 
			   queryFilter:(NSMutableArray *)queryFilter
			   otherParams:(NSMutableDictionary *)otherParams
				  delegate:(id<MCServer2ViewDelegate>)aDelegate{
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					key,@"key",
					layoutName,@"layout",
					queryFilter,@"ft",
					nil];
	
	methodName = @"getCustomForm";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (void)getCustomListAsync:(NSString *)layoutName 
			   queryFilter:(NSMutableArray *)queryFilter 
					  page:(NSString *)page 
			   otherParams:(NSMutableDictionary *)otherParams
				  delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					layoutName,@"layout",
					queryFilter,@"ft",
					page,@"p",
					nil];
	
	methodName = @"getCustomList";
	delegate = aDelegate;
	otherParameters = otherParams;
	
	[self sendAsyncJsonMessage];
}

- (void)getContactsAsync:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] init];
	methodName = @"getContacts";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)downloadContact:(NSString *)contactId
				   page:(int)page
			   delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					contactId, @"id",
					[NSString stringWithFormat:@"%d",page],@"p",
					nil];
	
	methodName = @"downloadContact";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)uploadContact:(NSString *)contactId
			  records:(NSMutableArray *)records
			 delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					contactId, @"id",
					records,@"r",
					nil];
	
	methodName = @"uploadContact";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

#pragma mark ---- 预览压缩文件列表 ----
- (void)getFileList:(NSString *)dataFrom 
		  fileParam:(NSMutableDictionary *)fileParam 
		   delegate:(id<MCServer2ViewDelegate>)aDelegate {
	[inParameters release];
	inParameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
					@"download",@"at",
					dataFrom,@"df",
					fileParam,@"fp",
					nil];
	methodName = @"getFileList";
	delegate = aDelegate;
	
	[self sendAsyncJsonMessage];
}

- (void)onException:(NSException*) e
{
	if (delegate && [delegate respondsToSelector:@selector(getServerError:returnMessage:)]) 
		[delegate getServerError:@"100" returnMessage:[e reason]];
	else {
		[[MCErrorManagement instance] doError:@"100" returnMessage:[e reason]];
	}
}

- (void)setAuthValue:(NSMutableDictionary *)params 
				 opt:(NSString *)opt
			 request:(NSMutableURLRequest *)request {
	return;
}

#pragma mark ---- 内部私有方法 ----

- (id)sendSyncJsonMessage:(NSString *)aMethodName parameters:(NSMutableDictionary *)aParameters {
	// 等待转圈图标开始转起来
	MClientAppDelegate *appDelegate = (MClientAppDelegate*)[[UIApplication sharedApplication] delegate];
	[appDelegate startActivityIndicatorView];
	
	NSMutableDictionary *requestDictionary = [NSMutableDictionary dictionary];
	[requestDictionary setObject:aMethodName forKey:@"opt"];
	[requestDictionary setObject:aParameters forKey:@"req"];
	NSString *jsonString = [requestDictionary JSONRepresentation];
	[aParameters release];
	
	MCLog(@"Request JSON String:\n%@",[jsonString length]>10000?[jsonString substringToIndex:10000]:jsonString);
	//本次流量统计
	int reqJsonLen = [jsonString length];
	
	MCUserDefaults* defaults = [MCUserDefaults instance];
	//本次流量存入缓存
	defaults.currentReq += reqJsonLen;
	//总流量存入缓存
	defaults.totalReq += reqJsonLen;
	//本日流量存入缓存
	defaults.currentDayReq += reqJsonLen;
	//本月流量存入缓存
	defaults.currentMonthReq += reqJsonLen;
	
	const char *utfString = [jsonString UTF8String];
	NSData *requestData = [NSData dataWithBytes:utfString length:strlen(utfString)];
	
	NSString *postLength = [NSString stringWithFormat:@"%d",[requestData length]];
	
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
	[request setURL:[NSURL URLWithString:serverServletUrl]];
	[request setHTTPMethod:@"POST"];
	[request setTimeoutInterval:20];
	[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
	[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:requestData];
	
	if (cookies != nil) {
		NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
		[request setAllHTTPHeaderFields:headers];
	}
	
	NSError *error = nil;
	
	NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &error ]; 
	[request release];
	
	if (error) {
		[appDelegate stopActivityIndicatorView];
		[[MCErrorManagement instance] doError:@"100" returnMessage:[error localizedDescription]];
		return nil;
	}
	cookies = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] retain];
	
	NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 
	
	MCLog(@"Response JSON String:\n%@",[responseString length]>10000?[responseString substringToIndex:10000]:responseString);
	//本次流量统计
	int resJsonLen = [responseString length];
	
	//本次流量存入缓存
	defaults.currentRes += resJsonLen;
	//总流量存入缓存
	defaults.totalRes += resJsonLen;
	//本日流量存入缓存
	defaults.currentDayRes += resJsonLen;
	//本月流量存入缓存
	defaults.currentMonthRes += resJsonLen;
	
	
	error = nil;
	NSDictionary *responseDictionary = [responseString JSONValue];
	[responseString release];
	
	if (error) {
		[appDelegate stopActivityIndicatorView];
		[[MCErrorManagement instance] doError:@"100" returnMessage:[error localizedDescription]];
		return nil;
	}
	
	returnCode = [responseDictionary objectForKey:@"code"];
	returnMessage = [responseDictionary objectForKey:@"msg"];
	returnValue = [responseDictionary objectForKey:@"res"];
	
	[appDelegate stopActivityIndicatorView];
	
	if (![returnCode isEqualToString:@"0"]) {
		[appDelegate stopActivityIndicatorView];
		[[MCErrorManagement instance] doError:@"99" returnMessage:returnMessage];
		return nil;
	}
	
	return returnValue;
	
}

- (void)sendAsyncJsonMessage {
	
	MClientAppDelegate *appDelegate = (MClientAppDelegate*)[[UIApplication sharedApplication] delegate];
	@try {
		NSMutableDictionary *requestDictionary = [NSMutableDictionary dictionary];
		[requestDictionary setObject:methodName forKey:@"opt"];
		[requestDictionary setObject:inParameters forKey:@"req"];
		NSString *jsonString = [requestDictionary JSONRepresentation];
		
		// 等待转圈图标开始转起来
		[appDelegate startActivityIndicatorView];
		
		//本次流量统计
		int jsonLen = [jsonString length];
		
		MCUserDefaults* defaults = [MCUserDefaults instance];
		//本次流量存入缓存
		defaults.currentReq += jsonLen;
		//总流量存入缓存
		defaults.totalReq += jsonLen;
		//本日流量存入缓存
		defaults.currentDayReq += jsonLen;
		//本月流量存入缓存
		defaults.currentMonthReq += jsonLen;
		
		
		MCLog(@"Request JSON String:\n%@",[jsonString length]>10000?[jsonString substringToIndex:10000]:jsonString);
		
		const char *utfString = [jsonString UTF8String];
		NSData *requestData = [NSData dataWithBytes:utfString length:strlen(utfString)];
		
		NSString *postLength = [NSString stringWithFormat:@"%d",[requestData length]];
		
		NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverServletUrl]];
		[request setHTTPMethod:@"POST"];
		[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
		[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
		[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
		[self setAuthValue:otherParameters opt:methodName request:request];
		[request setHTTPBody:requestData];
		if (cookies != nil) {
			NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
			[request setAllHTTPHeaderFields:headers];  
		}
		
		self.responseData = [NSMutableData data];
		self.httpConnection = [NSURLConnection connectionWithRequest:request delegate:self];
	}
	@catch (NSException * e) {
		[self onException:e];
	}
}

#pragma mark ----------------------------https 允许--------------------------------
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
	return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
	if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
		//if ([trustedHosts containsObject:challenge.protectionSpace.host])
		[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
	
	[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	@try {
		[self.responseData setLength:0];
	}
	@catch (NSException * e) {
		[self onException:e];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	@try {
		[self.responseData appendData:data];
	}
	@catch (NSException * e) {
		[self onException:e];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if (delegate && [delegate respondsToSelector:@selector(getServerError:returnMessage:)]) 
		[delegate getServerError:@"99" returnMessage:[error localizedDescription]];
	else {
		[[MCErrorManagement instance] doError:@"99" returnMessage:[error localizedDescription]];
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	MClientAppDelegate *appDelegate = (MClientAppDelegate*)[[UIApplication sharedApplication] delegate];
	@try {
		cookies = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] retain];
		//MCLog(@"------cookies=%@", cookies);
		
		NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
		
		//本次流量统计
		int jsonLen = [responseString length];
		
		MCUserDefaults* defaults = [MCUserDefaults instance];
		//本次流量存入缓存
		defaults.currentRes += jsonLen;
		//总流量存入缓存
		defaults.totalRes += jsonLen;
		//本日流量存入缓存
		defaults.currentDayRes += jsonLen;
		//本月流量存入缓存
		defaults.currentMonthRes += jsonLen;
		
		MCLog(@"Response JSON String:\n%@",[responseString length]>10000?[responseString substringToIndex:10000]:responseString);
		
		NSError *error;
		NSDictionary *responseDictionary = [responseString JSONValue];
		[responseString release];
		
		[appDelegate stopActivityIndicatorView];
		
		if (responseDictionary == nil)
		{
			returnCode = nil;
			returnValue = nil;
			if (delegate && [delegate respondsToSelector:@selector(getServerError:returnMessage:)]) {
				[delegate getServerError:@"99" returnMessage:[error localizedDescription]];
			} else {
				MCLog(@"error:%@",[error localizedDescription]);
			}
		}
		else {
			returnCode = [responseDictionary objectForKey:@"code"];
			returnMessage = [responseDictionary objectForKey:@"msg"];
			returnValue = [responseDictionary objectForKey:@"res"];
			if ([returnCode intValue] == 0) {
				if (delegate) {
					// 配置数据返回值保存到cache中
					[self saveToConfigCache:returnValue];
					
					if (delegate && [delegate respondsToSelector:@selector(getDataFromServerSuccess:)]) {
						[delegate getDataFromServerSuccess:returnValue];
					}
				}
			}
			else if ([returnCode intValue] == 4) {
				LoginBox *loginBox = [[LoginBox alloc] initWithTitle:@"\n\n\n\n" 
															 message:nil 
															delegate:self 
												   cancelButtonTitle:nil 
												   otherButtonTitles:nil];
				[loginBox show];
			}
			else {
				if (delegate && [delegate respondsToSelector:@selector(getServerError:returnMessage:)]) {
					[delegate getServerError:returnCode returnMessage:returnMessage];
				} else {
					MCLog(@"error:%@,%@",returnCode,returnMessage);
				}
			}
		}
	}
	@catch (NSException * e) {
		[self onException:e];
	} @finally {
		[inParameters release]; inParameters = nil;
	}
	
}

- (void)saveToConfigCache:(id)cacheValue
{
	if (self.cacheType == nil || cacheValue == nil) 
		return;
	if ([self.cacheType isEqualToString:@"Apps:"]) {
		[[MServerConfigCache sharedInstance] addMenu:cacheValue 
											  forKey:self.cacheType];
	}
	if ([self.cacheType isEqualToString:@"MenuOfApp:"]) {
		NSString *appId = [inParameters objectForKey:@"id"];
		[[MServerConfigCache sharedInstance] addMenu:cacheValue 
											  forKey:[NSString stringWithFormat:@"%@%@", self.cacheType, appId]];
	}
	else if ([self.cacheType isEqualToString:@"SubMenu:"]) {
		NSString *menuId = [inParameters objectForKey:@"id"];
		[[MServerConfigCache sharedInstance] addMenu:cacheValue 
											  forKey:[NSString stringWithFormat:@"%@%@", self.cacheType, menuId]];
	}
	else if ([self.cacheType isEqualToString:@"ListConfig:"]) {
		NSString *dataObjectName = [inParameters objectForKey:@"dto"];
		NSString *layoutName = [inParameters objectForKey:@"layout"];
		[[MServerConfigCache sharedInstance] addListLayout:cacheValue 
													forKey:[NSString stringWithFormat:@"%@:%@:%@", self.cacheType, dataObjectName, layoutName]];
	}
	else if ([self.cacheType isEqualToString:@"FormConfig:"]) {
		NSString *dataObjectName = [inParameters objectForKey:@"dto"];
		NSString *layoutName = [inParameters objectForKey:@"layout"];
		NSString *editable = [inParameters objectForKey:@"e"];
		[[MServerConfigCache sharedInstance] addFormLayout:cacheValue 
													forKey:[NSString stringWithFormat:@"%@:%@:%@:%@", self.cacheType, dataObjectName, layoutName, editable]];
	}
	else if ([self.cacheType isEqualToString:@"ReportConfig:"]) {
		NSString *reportName = [inParameters objectForKey:@"name"];
		[[MServerConfigCache sharedInstance] addReportQueryLayout:cacheValue 
														   forKey:[NSString stringWithFormat:@"%@:%@", self.cacheType, reportName]];
	}
	
}


@end